var api = require('../../utils/api.js');
var app = getApp();
Page({
  onShareTimeline:function(){
    return {
      title:"智克艺术 - 音乐 - "+this.data.classInfor.music_name,
      query:'musicId='+this.data.musicId,
      imageUrl:this.data.classInfor.img
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    isIn: 0,
    classInfor: {},
    keywords: '',
    idx: '',
    audioWay: 0, //播放方式 0顺序播放 1随机播放 2单曲循环
    playState: 0, //播放状态
    nowmiao: 0, //当前时间
    allmiao: 0, //全部时间
    nowMusic: [],
    audioList: [],
    currentSelect:1
  },
  // 改变当前选项
  currentSelect(e){
    const currentSelect = e.currentTarget.dataset.id
    this.setData({
      currentSelect
    })
    let url = 'Music/music_list'
    if(currentSelect==2)url = "Music/music_list_hot";
    wx.request({
      url:app.globalData.host+url,
      method:"POST",
      data:{
        id:this.data.musicId
      },
      success:res=>{
        if(res.data.code==2000){
          console.log(res.data.data);
          const audioList = res.data.data.music_list;
          this.setData({
            audioList
          })
        }else{
          wx.showToast({
            title: res.data.msg,
          })
        }
      },
      fail:err=>{
        wx.showToast({
          title: "网络错误",
        })
      }
    })
  },
  //搜索
  searchMusic(e) {
    this.setData({
      keywords: e.detail.value
    })
  },
  search1(e) {
    this.setData({
      // audioList:[],
      keywords: e.detail.value
    })
    this.getMusicList(this.data.musicId, this.data.keywords, 1,0)
  },
  //加入歌单
  addMusic() {
    api.fetchApi('music/join_the_playlist', {
      type: 1,
      id: this.data.classInfor.id,
      token: wx.getStorageSync('token')
    }).then(res => {
      wx.showToast({
        title: '收藏成功'
      })
    })
    this.getMusicList(this.data.musicId, this.data.keywords, 1,0)
  },
  addMusic1(e) {
    if (!wx.getStorageSync('type') ){
      wx.showToast({
        title: '请先登录！',
        icon:'none'
      })
      return 
    }
    var id = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + 'music/join_the_playlist',
      method: 'post',
      data: {
        type: 2,
        id,
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        console.log(res)
        wx.showToast({
          title: res.data.msg + '',
          icon:'none'
        })
        this.getMusicList(this.data.musicId, this.data.keywords, 1,0)
      }
    })
  },
  //播放全部
  playAllMusic() {
    // var bgAudioMannager = wx.getBackgroundAudioManager();
    
    // bgAudioMannager.title = this.data.audioList[0].name;
    // bgAudioMannager.singer = this.data.audioList[0].singer;
    // bgAudioMannager.coverImgUrl = this.data.audioList[0].cover;
    // bgAudioMannager.src = this.data.audioList[0].src;
    // this.nonitor()
   // this.audioInit1();
   this.setData({
     idx:0
   })
    var nowMusic = this.data.audioList[this.data.idx] || wx.getStorageSync('nowMusic');
    console.log(nowMusic)
    wx.setStorageSync('nowMusic', nowMusic)
    this.setData({
      nowMusic
    })
    this.audioInit1();
  },
  audioInit1() {
    var bgAudioMannager= wx.getBackgroundAudioManager();
    if (this.data.idx!==''){
      var nowMusic = this.data.audioList[this.data.idx];
       wx.setStorageSync('nowMusic', nowMusic)
    this.setData({
      nowMusic
    })
    }else{
       return
    }
    console.log(bgAudioMannager.currentTime,'前')
    var that = this
    bgAudioMannager.title = this.data.audioList[this.data.idx].name;
    bgAudioMannager.singer = this.data.audioList[this.data.idx].singer;
    bgAudioMannager.coverImgUrl = this.data.audioList[this.data.idx].cover;
    bgAudioMannager.src = this.data.audioList[this.data.idx].src;
    setTimeout(()=>{
      this.nonitor()
    },0)
  },
  // 监听播放变化来更改高亮显示文本
  changeActive(){
    let active = wx.getStorageSync('nowMusic')
    console.log(active)
  },
  pauseMusic() {
    console.log(this.data.playState)
    if (this.data.playState == 1) {
      //暂停
      wx.getBackgroundAudioManager().pause()
    } else {
      //播放
      if (wx.getBackgroundAudioManager().src == undefined) {
        this.audioInit1()
      }
      this.changeActive()
      wx.getBackgroundAudioManager().play()
    }
  },
  playMusic(e) {
    console.log(e)
    let id = e.currentTarget.dataset.id
    let musicId = this.data.musicId
    wx.navigateTo({
      url: '/pages/musicPlayer/musicPlayer?id='+id+'&musicId='+musicId,
    })
  },
  //拖动快进
  sliderChange(e) {
    this.setData({
      nowmiao: e.detail.value
    })
    wx.getBackgroundAudioManager().seek(this.data.nowmiao)
  },
  playFunc() {
    this.setData({
      playState: 1
    })
    console.log('设置播放状态为1', this.data.playState)
  },
  pauseFunc() {
    this.setData({
      playState: 0
    })
    console.log('设置播放状态为0', this.data.playState)
  },
  //下一曲
  nextPlay() {
    if (this.data.audioList.length == 0) {
      return
    }
    if (this.data.audioWay == 1) {
      //随机
      // console.log('随机', this.data.audioList.length)
      this.setData({
        idx: Math.floor(Math.random() * Math.round(this.data.audioList.length)) % this.data.audioList.length
      })
    } else if (this.data.audioWay == 0) {
      //顺序
      console.log('顺序')
      if (this.data.idx >= (this.data.audioList.length - 1)) {
        this.setData({
          idx: 0
        })
      } else {
        this.setData({
          idx: this.data.idx + 1
        })
      }
    } //单曲循环
    this.audioInit1();
  },
  //上一曲
  upPlay() {
    if (this.data.audioList.length == 0) {
      return
    }
    if (this.data.audioWay == 1) {
      //随机
      console.log('随机');
      this.setData({
        idx: Math.floor(Math.random() * 10) % this.data.audioList.length
      })
    } else if (this.data.audioWay == 0) {
      //顺序
      console.log('顺序')
      if (this.data.idx < 1) {
        this.setData({
          idx: this.data.audioList.length - 1
        })
      } else {
        this.setData({
          idx: this.data.idx - 1
        })
      }
    } //单曲循环
  //  wx.setStorageSync('nowMusic', this.data.audioList[this.data.idx])
    this.audioInit1()
  },
  //切换模式
  checkPlay(e) {
    if (this.data.audioWay > 1) {
      this.setData({
        audioWay: 0
      })
    } else {
      this.setData({
        audioWay: this.data.audioWay + 1
      })
    }
  },

  //监听音乐状态
  nonitor(){
    let bgAudioMannager = wx.getBackgroundAudioManager();
    bgAudioMannager.onPlay(() => {
      console.log('播放')
      this.playFunc()
    })
    bgAudioMannager.onPause(() => {
      console.log('暂停')
      this.pauseFunc()
    })
    bgAudioMannager.onEnded(() => {
      this.nextPlay()
    })
    bgAudioMannager.onTimeUpdate(() => {
     // console.log(bgAudioMannager.currentTime, 'onTimeUpdate')
    //  if(this.data.playState==1){
        // this.playFunc()
    //  }
      this.setData({
        nowmiao: Math.floor(bgAudioMannager.currentTime),
        allmiao: Math.floor(bgAudioMannager.duration),
      })
    })
      
  },
  //获取歌曲列表
  getMusicList(musicId, search, page,isSearch=1) {
    // if(!this.data.token){
    //   wx.showToast({
    //     title: '请先登录!',
    //     icon:'none'
    //   })
    //   setTimeout(() => {
    //     wx.switchTab({
    //       url: '/pages/personal/personal',
    //     })
    //   }, 1000);
    //   return
    // } //20201222取消登录限制
    var nowMusic = this.data.audioList[this.data.idx] || wx.getStorageSync('nowMusic');
    wx.setStorageSync('nowMusic', nowMusic)
    this.setData({
      nowMusic
    })
    api.fetchApi('music/music_list', {
      page,
      id: musicId,
      search,
      token: wx.getStorageSync('token') || ''
    }).then(res => {
      var count = res.count;
      var audioList = this.data.audioList,
      audioList1 = res.music_list;
      if (audioList1.length == 0 && page > 1) {
        return
      }
      page == 1 ? audioList = res.music_list : audioList = [...audioList, ...audioList1]
      if (audioList.length == 0) {
        console.log(nowMusic)
        this.setData({
          nowMusic
        })
      }
      this.setData({
        audioList,
        page,
        classInfor: res.class_info,
        count
      })
     var itemIndex= this.data.audioList.findIndex((item)=>item.id==wx.getStorageSync('nowMusic').id)
      if (wx.getStorageSync('nowMusic').music_class_id==this.data.musicId){
        this.setData({
          isIn:1
        })
      }
      itemIndex < 0 ? itemIndex='':''
      this.setData({
        idx: itemIndex
      })
       if (isSearch == 1){
        this.audioInit1();
      }
    })
  },
  // 监听音乐变化
  checkActive(){
    let active = wx.getStorageSync('nowMusic')
    let actId = active.id
    this.setData({
      actId
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    const that = this
    that.checkActive()
    var musicId = options.musicId;
    that.setData({
      playState: app.globalData.playState || 0,
      musicId,
      token:wx.getStorageSync('token')||options.token
    })
    that.getMusicList(musicId,'', 1,0);
    setInterval(() => {
      that.checkActive()
    }, 5000);
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log('页面卸载')
    app.globalData.playState=this.data.playState;
    this.nonitor();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var page = this.data.page || 1;
    page++;

    this.getMusicList(this.data.musicId, this.data.keywords, page,0)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})